package com.lsj.config.security.handler;

import cn.hutool.http.ContentType;
import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSONObject;
import com.lsj.core.response.CommonResult;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.Charset;

/**
 * @Author:lin.sj
 * @Data:2021/7/7 0:07
 * @Desc:
 */
@Component
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException e) throws IOException, ServletException {
        response.setContentType(ContentType.build(ContentType.JSON.getValue(), Charset.forName("UTF-8")));
        response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
        response.getWriter().write(JSONObject.toJSONString(CommonResult.error("当前尚未登录，请先登录！")));
    }
}
